package org.breathe.protocal.decode;

import io.netty.buffer.ByteBuf;
import lombok.Getter;
import org.breathe.datastruct.RedisBytes;
import org.breathe.protocal.Resp;

/**
 * @author: breathe
 * @createTime: 2025-05-12
 */
@Getter
public class BulkString extends Resp {
    private RedisBytes content;
    public static final byte[] NULL_BYTES = "-1\r\n".getBytes();
    public static final byte[] EMPTY_BYTES = "0\r\n\r\n".getBytes();
    public static final RedisBytes NULL = null;
    public BulkString(String content) {
        this.content = content == null ? null : new RedisBytes(content.getBytes());
    }
    public BulkString(RedisBytes content) {
        this.content = content;
    }
    public BulkString(byte[] content) {
        this.content = content == null ? null : new RedisBytes(content);
    }

    @Override
    public void encode(Resp resp, ByteBuf buffer) {
        buffer.writeByte('$');
        if (content == null) {
            buffer.writeBytes(NULL_BYTES);
        } else {
            int length = content.getBytes().length;
            if (length == 0) {
                buffer.writeBytes(EMPTY_BYTES);
            } else {
                buffer.writeBytes(String.valueOf(length).getBytes());
                buffer.writeBytes(CRLF);
                buffer.writeBytes(content.getBytes());
                buffer.writeBytes(CRLF);
            }
        }
    }

    @Override
    public String toString() {
        return "BulkString{" +
                "content=" + content +
                '}';
    }
}

